package api

import (
	"github.com/gin-gonic/gin"
	"time"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/request"
	"zsc-boot/app/customer/model/response"
	layModel "zsc-boot/app/system_layer/model"
	laySvc "zsc-boot/app/system_layer/service"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type ReportApi struct {
}

func (r *ReportApi) CustomerCount(ctx *gin.Context) {
	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)
	var data []response.CustomerCount
	if err := orm.GetDb().Model(&model.Customer{}).Group("is_new").Where("user_id in ?", subUserIds).
		Select("is_new,count(*) as count").Find(&data).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, data)
}

func (r *ReportApi) OrderByDep(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	userId := laySvc.GetUserID(ctx)

	userInfo, err := orm.Detail[layModel.ServiceUser](userId, "Role")
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	var depList []layModel.ServiceDepartment

	db := orm.GetDb()
	if userInfo.Role.Code != "root" {
		db = db.Where("principal = ?", userId)
	} else {
		db = db.Where("parent_id = 0")
	}

	if err = db.Preload("MembersList").Preload("Children.MembersList").
		Preload("Children.Children.MembersList").Find(&depList).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	var depArr []layModel.ServiceDepartment
	if userInfo.Role.Code != "root" {
		for _, dep := range depList {
			for _, v := range dep.Children {
				depArr = append(depArr, v)
			}
		}
	} else {
		depArr = depList
	}

	//获取名下所有子级部门
	var res []response.OrderByDep
	for _, dep := range depArr {
		tmp := response.OrderByDep{
			DepId:   dep.ID,
			DepName: dep.Name,
		}
		userList := laySvc.ServiceUsersService.GetUserListByDep([]layModel.ServiceDepartment{dep})
		userIds := make([]uint, 0, len(userList))
		for _, user := range userList {
			userIds = append(userIds, user.ID)
		}

		if err = orm.GetDb().Model(req.GetModel()).
			Where("user_id in ? and created_at > ? and created_at < ?", userIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59").
			Select("IFNULL(SUM(money), 0) AS count").Scan(&tmp.Count).Error; err != nil {
			web.FailResponse(ctx, err, "服务异常")
			return
		}
		res = append(res, tmp)
	}

	web.SuccessResponse(ctx, res)
}

func (r *ReportApi) UserRanking(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	//获取子级用户
	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)

	sub := orm.GetDb().Model(req.GetModel()).
		Where("user_id in ? and created_at > ? and created_at < ?",
			subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59").
		Select("user_id,sum(money) as count").Group("user_id")

	var res []response.UserRanking
	if err := orm.GetDb().Table("(?) as v", sub).Order("v.count desc").Preload("UserSimple").Find(&res).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, res)
}

func (r *ReportApi) ChannelConversion(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	//获取子级用户
	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)

	var res []response.ChannelConversion

	if err := orm.GetDb().Model(&model.Customer{}).
		Where("user_id in ? and created_at >= ? and created_at <= ?",
			subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59").
		Group("channel_id").Select("channel_id,count(*) as customer_count").Preload("ChannelInfo").
		Find(&res).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	customerIds := orm.GetDb().Model(&model.Customer{}).
		Where("user_id in ? and created_at >= ? and created_at <= ?",
			subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59").Select("id")

	customerIdsByOrder := orm.GetDb().Model(req.GetModel()).Where("customer_id in (?)", customerIds).
		Select("customer_id")

	var tmp1 []response.ChannelConversion
	if err := orm.GetDb().Model(&model.Customer{}).Where("id in (?)", customerIdsByOrder).Group("channel_id").
		Select("channel_id,count(*) as order_count").Find(&tmp1).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	for k, _ := range res {
		for _, v := range tmp1 {
			if v.ChannelId == res[k].ChannelId {
				res[k].OrderCount = v.OrderCount
			}
		}
	}

	web.SuccessResponse(ctx, res)
}

// OrderByDate 业绩走势图
func (r *ReportApi) OrderByDate(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	//过去12个月的数据
	var data []response.OrderByDate
	for i := 0; i < 12; i++ {
		data = append(data, response.OrderByDate{
			Date: time.Now().AddDate(0, -i, 0).Format("2006-01"),
		})
	}

	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)
	var dbData []response.OrderByDate

	if err := orm.GetDb().Model(req.GetModel()).Where("user_id in ?", subUserIds).Group("DATE_FORMAT(created_at, '%Y-%m')").
		Select("DATE_FORMAT(created_at, '%Y-%m') AS `date`,SUM(money) AS `count`").Find(&dbData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	for k, _ := range data {
		for _, v := range dbData {
			if data[k].Date == v.Date {
				data[k].Count = v.Count
			}
		}
	}
	web.SuccessResponse(ctx, data)
}

func (r *ReportApi) CustomerLevelGroup(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	res := []response.CustomerLevelGroup{{Level: "未知"}, {Level: "0"}, {Level: "1"}, {Level: "2"},
		{Level: "3"}, {Level: "4"}, {Level: "5"}}

	var dbData []response.CustomerLevelGroup
	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)

	if err := orm.GetDb().Model(&model.Customer{}).Where("user_id in ? and created_at > ? and created_at < ?",
		subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59").
		Group("JSON_EXTRACT(tag, '$.level')").
		Select("JSON_EXTRACT(tag, '$.level') AS level,COUNT(*) AS count").Find(&dbData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	for k, _ := range res {
		for _, v := range dbData {
			if v.Level == "" {
				res[0].Count = v.Count
				continue
			}
			if v.Level == res[k].Level {
				res[k].Count = v.Count
			}
		}
	}
	web.SuccessResponse(ctx, res)
}

func (r *ReportApi) CustomerFirstUserGroup(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	var res []response.CustomerFirstUserGroup

	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)
	db := orm.GetDb().Model(model.Customer{}).Where("first_user_id in ? and created_at >= ? and created_at <= ?",
		subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59")

	if req.ChannelId != 0 {
		db = db.Where("channel_id = ?", req.ChannelId)
	}

	if err := db.Group("first_user_id").Select("first_user_id,count(*) as count").
		Preload("UserSimple").Find(&res).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, res)
}

func (r *ReportApi) ImportCustomerFirstUserGroup(ctx *gin.Context) {
	var req request.OrderReq
	_ = ctx.ShouldBindQuery(&req)

	var res []response.CustomerFirstUserGroup

	subUserIds := laySvc.ServiceUsersService.GetSubUserIds(ctx)
	db := orm.GetDb().Model(&model.CustomerImportLog{}).
		Where("user_id in ? and created_at >= ? and created_at <= ?",
			subUserIds, req.StartDate+" 00:00:00", req.EndDate+" 23:59:59")

	if req.ChannelId != 0 {
		db = db.Where("channel_id = ?", req.ChannelId)
	}

	if err := db.Group("user_id").Select("user_id as first_user_id,count(*) as count").
		Preload("UserSimple").Find(&res).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, res)
}
func NewReportApi() *ReportApi {
	return &ReportApi{}
}
